function varargout = removeModelFolder(modelName, varargin)
%removeModelFolder Remove model folder
%   Remove the model folder from the current project.
%
%   语法：
%   removeModelFolder(ModelName)
%   removeModelFolder(ModelName, 'ProjectObj', prj)
%
%   输入参数：
%   modelName - 要移除的模型名称
%   varargin - 可选参数
%     'ProjectObj' - Name-Value参数，指定项目对象（默认调用currentProject()）

%   
% 解析输入参数
p = inputParser;
addParameter(p, 'ProjectObj', [], @(x) isempty(x) || isa(x, 'matlab.project.Project'));
parse(p, varargin{:});

if nargin < 1
    % Query for the model name if none is provided.
    modelName = char(inputdlg('Enter model name.', 'Model Name', [1 50]));
end

% Check if the model name is valid.
if ~isvarname(modelName)
    error([modelName, ' is an invalid model name. The model name must be a valid MATLAB variable name. See MATLAB help documentation for variable naming rules.']);
end

% Check if the model exists.
if ~exist(modelName)
    error(['Model ''', modelName, ''' does not exists.']);
end

% Get the model folder.
% 获取项目对象
if ~isempty(p.Results.ProjectObj)
    prj = p.Results.ProjectObj;  % 使用传入的项目对象
else
    prj = currentProject();  % 否则获取当前项目
end
% prjRoot = char(prj.RootFolder);
% modelDir = fullfile(prjRoot, 'DO_03_Design', modelName);
modelDir = ProjectPathManager.getDirPath('model root', modelName);

% Get the build and code verification folders for the model.
codeDirs = {ProjectPathManager.getDirPath('top model code', modelName), ...
            ProjectPathManager.getDirPath('ref model code', modelName), ...
            ProjectPathManager.getDirPath('code coverage', modelName), ...
            ProjectPathManager.getDirPath('code metrics', modelName), ...
            ProjectPathManager.getDirPath('code prover', modelName), ...
            ProjectPathManager.getDirPath('code review', modelName), ...
            ProjectPathManager.getDirPath('code standards', modelName), ...
            ProjectPathManager.getDirPath('bug finder', modelName), ...
            ProjectPathManager.getDirPath('test results', modelName)};

try
    % 性能优化：检测MATLAB版本，R2025a+支持批量路径移除
    % 基于开发规则：优化项目API调用次数，大幅提升删除性能
    isR2025aOrLater = ~isMATLABReleaseOlderThan('R2025a');
    
    if isR2025aOrLater
        % ==================== R2025a+ 批量优化版本 ====================
        % 批量收集所有需要移除的路径
        allPathsToRemove = {};
        
        % 收集模型目录的所有子路径
        modelRecDirStr = genpath(modelDir);
        modelRecDirs = regexp(modelRecDirStr, ';', 'split');
        modelRecDirs = modelRecDirs(~cellfun('isempty', modelRecDirs));
        for recDirIdx = 1:length(modelRecDirs)
            if exist(modelRecDirs{recDirIdx}, 'dir')
                allPathsToRemove{end+1} = modelRecDirs{recDirIdx}; %#ok<AGROW>
            end
        end
        
        % 收集代码目录的所有子路径
        for dirIdx = 1:length(codeDirs)
            codeRecDirStr = genpath(codeDirs{dirIdx});
            codeRecDirs = regexp(codeRecDirStr, ';', 'split');
            codeRecDirs = codeRecDirs(~cellfun('isempty', codeRecDirs));
            for recDirIdx = 1:length(codeRecDirs)
                if exist(codeRecDirs{recDirIdx}, 'dir')
                    allPathsToRemove{end+1} = codeRecDirs{recDirIdx}; %#ok<AGROW>
                end
            end
        end
        
        % 批量移除所有路径（性能优化核心：1次API调用代替几百次）
        if ~isempty(allPathsToRemove)
            try
                prj.removePath(allPathsToRemove);
                fprintf('✅ 批量移除了 %d 个路径（R2025a优化）\n', length(allPathsToRemove));
            catch ME
                warning(['批量移除路径失败: ', ME.message, '，回退到逐个移除']);
                % 回退到逐个移除
                for pathIdx = 1:length(allPathsToRemove)
                    try
                        prj.removePath(allPathsToRemove{pathIdx});
                    catch
                        warning(['Unable to remove ''', allPathsToRemove{pathIdx}, ''' from project path.']);
                    end
                end
            end
        end
        
        % 收集需要从项目移除的文件夹
        allFilesToRemove = {};
        if exist(modelDir, 'dir')
            allFilesToRemove{end+1} = modelDir;
        end
        for dirIdx = 1:length(codeDirs)
            if exist(codeDirs{dirIdx}, 'dir')
                allFilesToRemove{end+1} = codeDirs{dirIdx}; %#ok<AGROW>
            end
        end
        
        % 批量移除文件夹（尝试批量，如果失败则逐个处理）
        if ~isempty(allFilesToRemove)
            try
                % 尝试批量移除（如果API支持）
                prj.removeFile(allFilesToRemove);
                fprintf('✅ 批量移除了 %d 个文件夹引用（R2025a优化）\n', length(allFilesToRemove));
            catch
                % 如果批量不支持，逐个移除
                for fileIdx = 1:length(allFilesToRemove)
                    try
                        prj.removeFile(allFilesToRemove{fileIdx});
                    catch
                        warning(['Unable to remove ''', allFilesToRemove{fileIdx}, ''' from project.']);
                    end
                end
            end
        end
        
    else
        % ==================== 早期版本兼容模式 ====================
        % Remove folders from project path.
        modelRecDirStr = genpath(modelDir);
        modelRecDirs = regexp(modelRecDirStr, ';', 'split');
        modelRecDirs = modelRecDirs(~cellfun('isempty', modelRecDirs));
        for recDirIdx = 1:length(modelRecDirs)
            if exist(modelRecDirs{recDirIdx}, 'dir')
                try
                    prj.removePath(modelRecDirs{recDirIdx}); % Use try in case the path is already removed.
                catch
                    warning(['Unable to remove ''', modelRecDirs{recDirIdx}, ''' from project path.']);
                end
            end
        end
        for dirIdx = 1:length(codeDirs)
            codeRecDirStr = genpath(codeDirs{dirIdx});
            codeRecDirs = regexp(codeRecDirStr, ';', 'split');
            codeRecDirs = codeRecDirs(~cellfun('isempty', codeRecDirs));
            for recDirIdx = 1:length(codeRecDirs)
                if exist(codeRecDirs{recDirIdx}, 'dir')
                    try
                        prj.removePath(codeRecDirs{recDirIdx}); % Use try in case the path is already removed.
                    catch
                        warning(['Unable to remove ''', codeRecDirs{recDirIdx}, ''' from project path.']);
                    end
                end
            end
        end
        
        % Remove folders from project.
        if exist(modelDir, 'dir')
            try
                prj.removeFile(modelDir); % Use try in case the folder is already removed from project.
            catch
                warning(['Unable to remove ''', modelDir, ''' from project.']);
            end
        end
        for dirIdx = 1:length(codeDirs)
            if exist(codeDirs{dirIdx}, 'dir')
                try
                    prj.removeFile(codeDirs{dirIdx}); % Use try in case the folder is already removed from project.
                catch
                    warning(['Unable to remove ''', codeDirs{dirIdx}, ''' from project.']);
                end
            end
        end
    end
catch ME
    error(['Unable to remove ''', modelDir, ''' from project: ', ME.message]);
end

result.Message = ['Model folder ', modelDir, ' is successfully removed from the current project.'];
if nargout > 0
    varargout{1} = result;
end
disp(result.Message);

end
